import Vue from 'vue'
import VueRouter from 'vue-router'
import { deviceList, livestock, authority, user, company, ranch, deviceGroup } from './list'
import { getToken } from '@/until/token'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: 'login',
    // name: 'login',
    component: () => import('@/views/login.vue')
  },
  {
    // 会匹配所有路径
    path: '*',
    name: '404',
    component: () => import('@/views/404/404.vue')
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login.vue')
  },
  {
    path: '/index',
    name: 'index',
    component: () => import('@/views/index/index.vue'),
    children: [
      {
        path: '/panelIndex',
        name: 'panelIndex',
        component: () => import('@/views/index/panelIndex.vue'),
        meta: {
          title: '大屏'
        }
      }
    ]
  },
  ...deviceList,
  ...livestock,
  ...authority,
  ...user,
  ...company,
  ...ranch,
  ...deviceGroup
]

const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}
router.beforeEach((to, from, next) => {
  if (to.path !== '/login' && !getToken()) {
    next('/login')
    sessionStorage.clear()
  } else {
    next()
  }
})

export default router
